<?php
// 后台函数库
use OSS\OssClient;
use OSS\Core\OssException;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
function curl_get($url, array $params = array(), $timeout = 1)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
}
function total_game_user_online_number(){
    $total_game_user_online_number =count(array_merge(user_online_arr_B(),user_online_arr_A()));
    return $total_game_user_online_number;
}
function isJson($data = '', $assoc = false) {
    $data = json_decode($data, $assoc);
    if ($data && (is_object($data)) || (is_array($data) && !empty(current($data)))) {
        return true;
    }
    return false;
}
/**
 * 系统操作日志
 * @param string
 * @author 张志远<466180170@qq.com>
 * @return  $model:模块名称  $controller:控制器名称  $title:错误内容
 */
function System_Operation_Log($user,$model,$controller,$title=''){
    $time =date('Y-m-d H:i:s',time());
    file_put_contents('System_Operation_Log.txt', '模块名称: '.$model.' 。控制器:'.$controller.' 。操作内容:'.$title.' 。操作人: '.$user.' 。操作时间记录: ' .$time. "\r\n", FILE_APPEND);
}
/*异常处理*/
function Exception_handling_reporting_typeofget(){
    $time =date('Y-m-d H:i:s',time());
    $str ="<h1>Whitelabel Error Page</h1>
                This application has no explicit mapping for /error, so you are seeing this as a fallback.
                ".$time."</br>
                There was an unexpected error (type=Method Not Allowed, status=40001).</br>
                Request method 'GET' not supported";
    die($str);
}

/**
 * 返回道具详细信息
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function  Specific_parameters_prop_Details($PropID){
    if(is_numeric($PropID)){
        $json_string = file_get_contents(env('PLATFORM.prop_url'));
        $data = json_decode($json_string, true);
        $results=[];
        foreach($data as $k=>$v){
            if($k == $PropID){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }
}

/**
 * 返回埋点详细信息
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function  Specific_parameters_point_name($point_ID){
    $json_string = file_get_contents(env('PLATFORM.point_url'));
    $data = json_decode($json_string, true);
    $reslult =[
        'name'=>'暂无配置'
    ];
    foreach($data as $k=>$v){
        if($v['point_ID'] == $point_ID){
            $reslult['name']=$v['name'];
        }
    }
    return $reslult['name'];
}

/**
 * 返回道具详细信息
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function  Specific_parameters_Recharge_channel_arr(){
        $json_string = file_get_contents(env('PLATFORM.recharge_url'));
        $data = json_decode($json_string, true);
        /*三维数组转化二维数组*/
        $result=array_reduce($data, 'array_merge', array());
        return $result;
}
/**
 * 返回道具详细信息
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function  Specific_parameters_Recharge_room_arr(){
    $json_string = file_get_contents(env('PLATFORM.room_url'));
    $data = json_decode($json_string, true);
    return $data;
}

/**
 * 返回渠道详细信息
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function  Specific_parameters_Recharge_channel($channel_id){
    if(is_numeric($channel_id)){
        $json_string = file_get_contents(env('PLATFORM.recharge_url'));
        $data = json_decode($json_string, true);
        $results=[];
        foreach($data as $k=>$v){
            if($k == $channel_id){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }
}
/**
 * 返回充值的商品的具体参数
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_commodities($goodsid){
    if(is_numeric($goodsid)){
        $json_string = file_get_contents(env('PLATFORM.Store_url'));
        $data = json_decode($json_string, true);
        $results=[];
        foreach($data as $k=>$v){
            if($k == $goodsid){
                $results=$v;
            }
        }
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }
}

/**
 * 返回充值的商品的具体参数
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_commodities_pay_type($tradetype){
    if(is_numeric($tradetype)){
        $json_string = file_get_contents(env('PLATFORM.paytype_url'));
        $data = json_decode($json_string, true);
        $results=[];
        foreach($data as $k=>$v){
            if($k == $tradetype){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }
}


/**
 * 返回充值的商品的具体参数
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_commodities_arr(){
        $json_string = file_get_contents(env('PLATFORM.Store_url'));
        $data = json_decode($json_string, true);
        /*二维数组转化一维数组*/
        $result=array_reduce($data, 'array_merge', array());
        return $result;
}

/**
 * 返回充值的支付类型
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_commodities_pay_type_arr(){
        $json_string = file_get_contents(env('PLATFORM.paytype_url'));
        $data = json_decode($json_string, true);
        /*二维数组转化一维数组*/
        $result=array_reduce($data, 'array_merge', array());
        return $result;
}
/**
 * 房间
 * @author 张志远 <466180170@qq.com>
 * @return mixed  GameName :游戏房间  GameLevel:场次
 * 游戏房间 +场次决定房间
 */
function room_type($GameName,$GameLevel){
    $json_string = file_get_contents(env('PLATFORM.room_url'));
    $data = json_decode($json_string, true);
    $reslult =[
        'name'=>'游戏大厅'
    ];
    foreach($data as $k=>$v){
        if($v['GameName'] == $GameName && $v['GameLevel']== $GameLevel){
            $reslult['name']=$v['name'];
        }
    }
    return $reslult['name'];
}

/*二维数组去重*/
function assoc_unique($arr, $key) {
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) { //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}
/**
 *
 * @author 张志远 <466180170@qq.com>
 * @return mixed
 * 获取充值渠道名称
 */
function get_channel_name($channel_id){
    return empty(Specific_parameters_Recharge_channel($channel_id))? $channel_id :Specific_parameters_Recharge_channel($channel_id)['name'];
}
/**
 *
 * @author 张志远 <466180170@qq.com>
 * @return mixed
 * 获取充值渠道名称
 */
function get_Billing_name($Billing_id){
    return empty(Specific_parameters_commodities($Billing_id))? $Billing_id :Specific_parameters_commodities($Billing_id)['Title'];
}

/**
 *
 * @author 张志远 <466180170@qq.com>
 * @return mixed
 * 获取道具名称
 */
function get_prop_name($PropID){
    return empty(Specific_parameters_prop_Details($PropID))? $PropID :Specific_parameters_prop_Details($PropID)['name'];
}
/**
 *
 * @author 张志远 <466180170@qq.com>
 * @return mixed
 * 获取道具描述
 */
function get_prop_description($PropID){
    return empty(Specific_parameters_prop_Details($PropID))? '--' :Specific_parameters_prop_Details($PropID)['Description'];
}
/**
 *
 * @author 张志远 <466180170@qq.com>
 * @return mixed
 * 获取支付方式名称
 */
function get_pay_type($tradetype){
    return empty(Specific_parameters_commodities_pay_type($tradetype))? $tradetype :Specific_parameters_commodities_pay_type($tradetype)['name'];
}
/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * $widthArr表格宽度
 * @author static7
 */
function excelExport($fileName = '', $headArr = [], $data = [],$widthArr = []) {
    require_once '../extend/PHPExcel/PHPExcel.php';
    $fileName .= "_" . date("Y_m_d", Request::instance()->time()) . ".xls";
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties();
    $keywidth = ord("A");  // 设置表头
    foreach($widthArr as $v){
        $colum = chr($keywidth);
        $objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth($v);
        $keywidth += 1;
    }
    $key = ord("A");  // 设置表头
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        //下面注释的这行代码是让表头拥有筛选功能，根据需要取消注释即可
        //$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) {          // 行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入
            $objActSheet->setCellValue(chr($span) . $column, $value);
            $span++;
        }
        $column++;
    }
    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename=' . $fileName);
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); // 文件通过浏览器下载
    exit();
}

function server_name($extra){
    $json =json_decode($extra,true);
    return $json['serverip'];
}
/**
 *      ip定位区域
 *      @return String
 */
function location_ip_area($ip){
    $url = env('LOCATION_PARAMETER_KEY_URL_IP').$ip.'&output=json'.'&key='.env('LOCATION_PARAMETER_KEY');
    $info =json_decode(file_get_contents($url),true);
    if(empty($info['province']) && empty($info['city'])){
        $area_str ='IP地址无效';
    }else{
        $area_str =$info['province'].$info['city'];
    }
    return $area_str;
}

function user_online_arr(){
      $data =array_merge(user_online_arr_B(),user_online_arr_A());
      return $data;
}

/**
 *  用户在线人数B组
 * @param string
 * @author 张志远<466180170@qq.com>
 */
function user_online_arr_B(){
    $user_arr_amout_B = json_decode(curl_get(env('ONLINE_USER_INTERFACE_AMOUT_B')), true);
    $user_arr_game_B = json_decode(curl_get(env('ONLINE_USER_INTERFACE_GAME_B')), true);
    if(!empty($user_arr_amout_B) && !empty($user_arr_game_B)){
        $data =array_merge($user_arr_game_B,$user_arr_amout_B);
    }else{
        $data =$user_arr_amout_B;
    }
    $data_arr =[];
    if(!empty($data)){
        $data_arr =arr_unset($data,'UserID');
    }
    return $data_arr;
}

/**
 *  用户在线人数B组
 * @param string
 * @author 张志远<466180170@qq.com>
 */
function user_online_arr_A(){
    $user_arr_amout_A = json_decode(curl_get(env('ONLINE_USER_INTERFACE_AMOUT_A')), true);
    $user_arr_game_A = json_decode(curl_get(env('ONLINE_USER_INTERFACE_GAME_A')), true);
    if(!empty($user_arr_amout_A) && !empty($user_arr_game_A)){
        $data =array_merge($user_arr_game_A,$user_arr_amout_A);
    }else{
        $data =$user_arr_amout_A;
    }
    $data_arr =[];
    if(!empty($data)){
        $data_arr =arr_unset($data,'UserID');
    }
    return $data_arr;
}
/**
 * 去重
 * @param int
 * @author 张志远 <466180170@qq.com>
 * array_slice(array,offset,length,preserve)
 * @return mixed
 */
function arr_unset($arr,$key){
    $res = array();
    foreach ($arr as $value) {
        if(isset($res[$value[$key]])){//查看有没有重复项
            unset($value[$key]); //有：销毁
        }
        else{
            $res[$value[$key]] = $value;
        }
    }
    return $res;
}

/**
 * 短信发送
 * @param $to    接收人
 * @param $model 短信模板ID
 * @param $code   短信验证码
 * @return json
 * @
 */
function send_sms($to, $model, $code)
{
    require_once '../extend/alisms/vendor/autoload.php';
    Config::load(); //加载区域结点配置
    $config = '根据你的实际情况读取配置文件或读取数据库，本项目是将配置写入数据库实现';
    $accessKeyId = 'LTAIuFOC03oi9x2t';
    $accessKeySecret = 'JoCwWrCm1OsH1HJ10xOOWJMHikNdrl';
    $templateParam = $code;
    //短信签名
    $signName = '河马游戏';
    //短信模板ID
    switch ($model) {
        case 1:
            $templateCode = 'SMS_168410170';  // 注册登录短信验证码模板
            break;
        case 2:
            $templateCode = $config['model_code_reset'];  // 重置密码短信验证码模板
            break;
    }
    //短信API产品名（短信产品名固定，无需修改）
    $product = "Dysmsapi";
    //短信API产品域名（接口地址固定，无需修改）
    $domain = "dysmsapi.aliyuncs.com";
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
    $region = "cn-hangzhou";
    // 初始化用户Profile实例
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
    // 增加服务结点
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    // 初始化AcsClient用于发起请求
    $acsClient = new DefaultAcsClient($profile);
    // 初始化SendSmsRequest实例用于设置发送短信的参数
    $request = new SendSmsRequest();
    // 必填，设置雉短信接收号码
    $request->setPhoneNumbers($to);
    // 必填，设置签名名称
    $request->setSignName($signName);
    // 必填，设置模板CODE
    $request->setTemplateCode($templateCode);
    // 可选，设置模板参数
    if ($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }
    //发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);
    //返回请求结果
    $result = json_decode(json_encode($acsResponse), true);
    // 具体返回值参考文档：https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.YSe8FK
    return $result;
}

/**
 *      把秒数转换为天时分秒的格式
 *      @param Int $times 时间，单位 秒
 *      @return String
 */
function secToTime($times){
    $result = '0天0小时0分钟0秒';
    if ($times>0) {
        $day = floor($times/(3600*24));

        $remain_sec = $times%(3600*24);
        $hour = floor($remain_sec/3600);

        $remain_sec = $remain_sec%3600;
        $minutes = floor($remain_sec / 60);
        $sec = $minutes%60;

        $result = $day.'天'.$hour.'小时'.$minutes.'分钟'.$sec.'秒';
    }
    return $result;
}

/**
 * 返回错误信息代码
 * @author chenhan
 * @access public
 * @param  mixed    $data           提示信息或是数组
 * @param  int      $returncolla    判断是否加密：1加密，0不加密
 * @return string   返回json数据
 **/
function puterror($data,$returncolla=0){
    //用户需要看到的文字信息，手动加入$error数组
    //不需要的给数字：例如：puterror(100,$returncolla);
    //返回参数就是：'{"status": 0,"msg": "错误：100"}'
    $error = array(
        1       =>  '参数错误',
        2       =>  '未查到相关信息',
        3       =>  '操作失败',
        201       =>  '身份标识不存在',
        202       =>  '礼包已领取',
    );
    //成功时，输出data数组
    if(is_array($data)){
        $res['status']=0;
        $res=array_merge($res,$data);
    }else{
        $res['status']=0;
        if(is_numeric($data)){
            if(key_exists($data,$error)){
                $res['msg']=$error[$data];
            }else{
                $res['msg'] = '错误：'.$data;
            }
        }else{
            $res['msg']=$data;
        }
    }
    $return = json_encode($res);
    //判断是否需要加密
    if($returncolla == 1){
        $iv = config('AES_token.iv');
        $key = config('AES_token.key');
        $encrypted = openssl_encrypt($return, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
        die(base64_encode($encrypted));
    }else{
        die($return);
    }
}

/**
 * 返回成功信息代码
 * @author chenhan
 * @access public
 * @param  mixed  $data          提示信息或是数组
 * @param  int    $returncolla   判断返回参数是否需要加密：1加密，0不加密
 * @return string      返回数组
 **/
function putsuccess($data,$returncolla=0){
    $succ = array(
        1 => '操作成功！',
        2 => '注册成功',
        3 => '提交成功',
        4 => '图片保存成功',
        5 => '修改成功',
        6 => '开通成功',
        7 => '编辑成功',
        8 => '发布成功',
        9 => '保存成功',
        10 => '删除成功',
        11 => '回复成功'
    );
    //成功时，输出data数组
    if(is_array($data)){
        $res['status']=1;
        $res['msg'] = '操作成功';
        $res=array_merge($res,$data);
    }else{
        $res['status']=1;
        if(is_numeric($data)){
            $res['msg']=$succ[$data];
        }else{
            $res['msg']=$data;
        }
    }
    $return = json_encode($res);
    //判断是否需要加密
    if($returncolla == 1){
        $iv = config('AES_token.iv');
        $key = config('AES_token.key');
        $encrypted = openssl_encrypt($return, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
        die(base64_encode($encrypted));
    }else{
        die($return);
    }
}
/**
 * redis连接
 * @author chenhan
 * @access public
 * @param  mixed  $data          提示信息或是数组
 * @param  int    $returncolla   判断返回参数是否需要加密：1加密，0不加密
 * @return string      返回数组
 **/
function connect_redis_db_2(){
    $redis = new Redis();
    $redis->connect(env('REDIS.host'),env('REDIS.port'));
    $redis->auth(env('REDIS.auth'));
    $redis->select(env('REDIS.select_2'));
    return $redis;
}
/**
 * redis连接
 * @author chenhan
 * @access public
 * @param  mixed  $data          提示信息或是数组
 * @param  int    $returncolla   判断返回参数是否需要加密：1加密，0不加密
 * @return string      返回数组
 **/
function connect_redis_db_0(){
    $redis = new Redis();
    $redis->connect(env('REDIS.host'),env('REDIS.port'));
    $redis->auth(env('REDIS.auth'));
    $redis->select(env('REDIS.select_0'));
    return $redis;
}
/**
 * 限时道具
 * @author chenhan
 * @access public
 * @param  mixed      UserID
 * @param  int
 * @return string    返回数组
 **/
function time_prop_arr($UserID){
    $redis_0 =connect_redis_db_0();
    $redis_2 =connect_redis_db_2();
    $data=[];
    $crab_arr=json_decode($redis_2->hGet(env('TIME_PROP.crab').'2020'.date('W'),$UserID),true);
    $hunter_arr=json_decode($redis_0->hGet(env('TIME_PROP.hunter').date("Ymd",time()),$UserID),true);
    $hyperion_score=json_decode($redis_0->zScore(env('TIME_PROP.hyperion').'2020'.date('W'),$UserID),true);
    if(!empty($crab_arr)){
        $data=array_merge($data,$crab_arr);
    }
    if(!empty($hunter_arr)){
        $data=array_merge($data,$hunter_arr);
    }
    if(!empty($hyperion_score)){
        $hyperion_arr=[[10186,$hyperion_score]];
        $data=array_merge($data,$hyperion_arr);
    }
    if(!empty($data)){
        foreach($data as $k=>$v){
            $data[$k]['PropID']=$v[0];
            $data[$k]['prop_name']=get_prop_name($v[0]);
            $data[$k]['desc']=get_prop_description($v[0]);
            $data[$k]['Counts']=$v[1];
        }
    }
    return $data;
}
/**
 * 限时道具
 * @author chenhan
 * @access public
 * @param  mixed
 * @param  int
 * @return string    返回数组
 **/
function time_online_count_arr($data=array(),$arr=array(),$type_field,$field){
    $arr_c=array_count_values(array_column($arr,$type_field));
    $data_Arr =[];
    foreach($data as $k=>$value){
        if(!empty($arr_c[$value[$field]])){
            $data_Arr[$k]['name'] =$value[$field];
            $data_Arr[$k]['count'] =$arr_c[$value[$field]];
        }else{
            $data_Arr[$k]['name'] =$value['name'];
            $data_Arr[$k]['count']=0;
        }
    }
    return $data_Arr;
}



